# py module

from turnited._config import *
from turnited.page._base import TurnitedPageBase
from turnited.model.team import TeamModel
from turnited.model.liga import LigaModel

import wsgiref.handlers
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

from google.appengine.ext.db import djangoforms
from google.appengine.api import datastore_errors
from django import newforms as forms

######################################################################

# list

class LigaList(TurnitedPageBase):
    def get(self):
        query = LigaModel.all().order('name')
        entries = [ r for r in query.fetch(limit=100) ]
        for lg in entries:
            qt = db.GqlQuery('SELECT __key__ FROM TeamModel WHERE liga = :liga', liga=lg.key())
            lg.size = qt.count()
        template_values = {
            'entries': entries,
            'error': self.request.get('error'),
            'msg': self.request.get('msg'),
            }
        self._commonRender(BASE_THTML + '/liga_list.html', template_values)

# dialogs

class LigaEdit(TurnitedPageBase):
    def get(self):
        _lkey = db.Key(self.request.get('id'))
        query = LigaModel.all()
        query.filter('__key__ =', _lkey)
        entries = query.fetch(limit=1)
        if len(entries)>0:
            liga = entries[0]
            # get teams
            qt = TeamModel.all()
            qt.filter('liga =', _lkey)
            teams = ", ".join([ "<a href='team_edit?key=%s'>%s</a>"% (t.key(), t.name)  for t in qt.fetch(100) ])
            if qt.count(100) >= 100: teams = teams + "..."
            # html
            self._commonRender(BASE_THTML + '/liga_edit.html',  { 'entry': liga, 'teams':teams } )
        else:
            self.redirect('liga_list')


class LigaNew(TurnitedPageBase):
    def get(self):
        self._commonRender(BASE_THTML + "/liga_new.html", {})

# actions

class LigaAdd(TurnitedPageBase):
    def post(self):
        # check 'name' exists
        query = LigaModel.all()
        query.filter('name =', self.request.get('name'))
        entries = query.fetch(limit=1)
        if len(entries) > 0:
            ### @todo MSG
            self.redirect('liga_list')
            return
        # new
        liga = LigaModel( name=self.request.get('name') )
        liga.put()
        self.redirect('liga_list')


class LigaSave(TurnitedPageBase):
    def post(self):
        query = LigaModel.all()
        query.filter('__key__ =', db.Key(self.request.get('id')))
        entries = query.fetch(limit=1)
        if len(entries)>0:
            liga = entries[0]
            dirty = False
            if liga.name != self.request.get('name'):
                # check 'name' exists
                q2 = LigaModel.all()
                q2.filter('name =', self.request.get('name'))
                e2 = q2.fetch(limit=1)
                if len(e2) > 0:
                    ### @todo MSG
                    self.redirect('liga_list?error=Liga+mit+Name+existiert+schon')
                    return
                liga.name = self.request.get('name')
                dirty = True
            if dirty:
                liga.put()
                self.redirect('liga_list?msg=Liga+gespeichert')
            else:
                self.redirect('liga_list?msg=nix+getan')


class LigaDel(TurnitedPageBase):
    def get(self):
        if True:
            query = LigaModel.all()
            query.filter('__key__ =', db.Key(self.request.get('id')))
            entries = query.fetch(limit=1)
            if len(entries)>0:
                liga = entries[0]
                liga.delete()
            self.redirect('liga_list')

#
